package com.atguigu.gulimail.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimail.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimail.product.entity.*;
import com.atguigu.gulimail.product.service.*;
import com.atguigu.gulimail.product.vo.AttrGroupRelationVO;
import com.atguigu.gulimail.product.vo.AttrRespVo;
import com.atguigu.gulimail.product.vo.AttrVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.product.dao.AttrDao;
import org.springframework.util.StringUtils;

@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {


    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    CategoryService categoryService;
    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    ProductAttrValueService attrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttrVo(AttrVo attrVo) {
        //AttrVo 和AttrEntity的不同一点在于
        // 浏览器发送的请求带有一个数据 不是AttrEntity属性里有的。 如果在加一个属性。然后还要@TableFilet(Exist=false）
        //这种注解加多了就很 复杂。 所以 写一个新的实体类 专门用来接受处理数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        //这也用到了中间表关联。
        this.save(attrEntity);

        if (attrVo.getAttrType() == ProductConstant.ProductType.BASE_TYPE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }


    }

    //首先 attrType是 pms_attr表中的一个字段。
    @Override
    public PageUtils queryDetils(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.ProductType.BASE_TYPE.getCode() : ProductConstant.ProductType.SALE_TYPE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(warper -> {
                warper.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        Stream<AttrEntity> stream = records.stream();
        List<AttrRespVo> attrRespVoList = stream.map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //获取分类名称。
            Long catelogId1 = attrEntity.getCatelogId();
            CategoryEntity byId = categoryService.getById(catelogId1);
            if (byId != null) {
                attrRespVo.setCatelogName(byId.getName());
            }
            //获取分组名称。
            //逻辑是 从 （属性和属性分组关系）表 获取到attr_group_id 然后调用attr_groupService 获取到attrgroupName
            if ("base".equalsIgnoreCase(attrType)) {
                QueryWrapper<AttrAttrgroupRelationEntity> attr_id = new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId());
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(attr_id);
                if (attrAttrgroupRelationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }

            }

            return attrRespVo;
        }).collect(Collectors.toList());


        pageUtils.setList(attrRespVoList);
        return pageUtils;

    }

    @Override
    public AttrRespVo getAttrRespVoById(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        //从关系表通过attrid 过去到attrgroupid
        //设置分组数据
        if (attrRespVo.getAttrType() == ProductConstant.ProductType.BASE_TYPE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrId));
            Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
            //attrgroupService get by id
            AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
            if (attrGroupEntity != null) {
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                attrRespVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
            }
        }

        //设置分类数据
        Long catelogId = attrEntity.getCatelogId();
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
            attrRespVo.setCatelogId(categoryEntity.getCatId());
        }
        //获取 完整分类路径
        Long[] catelogPath = categoryService.getCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);


        log.info("============>attrRespVo:{}", attrRespVo);
        return attrRespVo;
    }

    @Override
    public void updateAttrRespVo(AttrRespVo attrRespVo) {

        //先完成基本的修改。
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrRespVo, attrEntity);
        this.updateById(attrEntity);

        //修改分组关联。直接用update 一个attr_id  一个attr_group_id
        if (attrRespVo.getAttrType() == ProductConstant.ProductType.BASE_TYPE.getCode()) {

            Long attrId = attrRespVo.getAttrId();
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrId);
            attrAttrgroupRelationEntity.setAttrGroupId(attrRespVo.getAttrGroupId());

            attrAttrgroupRelationService.saveOrUpdate(attrAttrgroupRelationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        }


    }

    @Override
    public List<AttrEntity> getAttrsByGroupId(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        if (attrList.size() > 0) {
            List<Long> ids = attrList.stream().map(relationEntity -> {

                return relationEntity.getAttrId();
            }).collect(Collectors.toList());

            List<AttrEntity> attrEntities = this.listByIds(ids);
            return attrEntities;
        }
        return null;

    }

    @Override
    public void deleteBatch(AttrGroupRelationVO[] relationVOS) {
        //批量删除。
        //首先把vos转换成list.
        List<AttrGroupRelationVO> attrGroupRelationVOS = Arrays.asList(relationVOS);

        List<AttrAttrgroupRelationEntity> relationEntities = attrGroupRelationVOS.stream().map(attrGroupRelationVO -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attrGroupRelationVO, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(relationEntities);

    }

    //获取当前分组没有关联的所有属性/
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1当前分组只能关联自己所属的分类里面的所有属性。
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2当前分组只能关联别的分组没有引用的属性。
        //2.1找到当前分类下的其他分组
        List<AttrGroupEntity> catelog_id = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //通过stream流的映射规则，将一个实体类集合转换成一个Long类型的集合。
        List<Long> groupids = catelog_id.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //2.2找到这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupids));
        List<Long> attrids = relationEntities.stream().map(item -> {
            Long attrId = item.getAttrId();

            return attrId;
        }).collect(Collectors.toList());
        //2.3从属性表中剔除这些属性。
        QueryWrapper<AttrEntity> warper = new QueryWrapper<>();
        if (attrids != null && attrids.size() > 0) {
            warper.notIn("attr_id", attrids);
        }
        warper.eq("catelog_id", catelogId).eq("attr_type", ProductConstant.ProductType.BASE_TYPE.getCode());
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            warper.and(w -> {
                warper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), warper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;

    }

    @Override
    public List<ProductAttrValueEntity> getAttrValuesBySpuId(Long spuId) {


        List<ProductAttrValueEntity> spu_id = attrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));

        return spu_id;
    }

    @Override
    public List<Long> getSearched(List<Long> attrIds) {
        List<AttrEntity> searchList = this.list(new QueryWrapper<AttrEntity>().in("attr_id", attrIds).eq("search_type", 1));
        List<Long> collect = searchList.stream().map(m -> {
            return m.getAttrId();
        }).collect(Collectors.toList());

        return collect;
    }

}